package com.hongtu.supplychain.finance.log;

import com.google.gson.Gson;
import com.hongtu.supplychain.finance.util.Constants;
import org.apache.log4j.Logger;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;


/**
 * Created by Administrator on 2016/9/28.
 */
@Order(1)
@ControllerAdvice(basePackages = {"com.hongtu.supplychain.finance"})
public class ResponseBodyLogger implements ResponseBodyAdvice {

    private Logger logger = Logger.getLogger(getClass());

    private static final List<String> noLogUrlList = Arrays.asList(new String[]{"/hongtu/user/getCargoOwners"});

    private static final Gson gson = new Gson();

    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest request, ServerHttpResponse response) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        // 非get请求才需要记录响应报文
        if(!servletRequest.getMethod().equals(HttpMethod.GET)) {
            HttpServletRequest httpServletRequest = servletRequest.getServletRequest();
            // 过滤一些响应数据比较大的请求
            logger.error("responseID: " + httpServletRequest.getAttribute(Constants.REQUEST_OR_RESPONSE_ID) + "  response address: [" + servletRequest.getURI()  +
                    "], mediaType: [" + mediaType.toString()+
                    "], responseBody: <" + (noLogUrlList.contains(request.getURI().getPath()) ? "": gson.toJson(o)) + ">");
        }
        return o;
    }
}
